<template>
	<view class="repastPage d-flex f-column" :style="{'--color': color, '--total-height': totalHeight + 'px'}">
		<view class="topBg width" :style="{backgroundImage: 'url(' + $imgUrls(storeInfo.store_index_bj) + ')'}"></view>
		<view class="head white zIndex">
			<view :style="{height: System.statusBarHeight + 'px'}"></view>
			<view class="d-flex a-center p-left30 p-right30 m-bot20"
				:style="{width: navWidth + 'px', 'height': navHeight + 'px'}">
				<view class="flex-1 d-flex a-center">
					<view class="tab m-right20" :class="{'active': way == 0}" @click="switchMode(0)"
						v-if="startUp.delivery.indexOf('2') > -1">自提</view>
					<view class="line bgwhite m-right20" v-if="startUp.delivery.indexOf('1,2') > -1"></view>
					<view class="tab" :class="{'active': way == 1}" @click="switchMode(1)"
						v-if="startUp.delivery.indexOf('1') > -1">外送</view>
				</view>
				<view class="search bor_radius flexac" @click="toUrl('/pages/classify/searchMode')">
					<text class="iconfont icon-btn_search size36"></text>
				</view>
			</view>
			<view class="p-left30 w-fit" v-if="storeInfo && way == 0" @click="toStores">
				<view class="d-flex a-center m-bot10">
					<text class="iconfont icon-shoucang7 m-right10"></text>
					<view class="size32 m-right10">{{ storeInfo.name }}</view>
					<text class="iconfont icon-xiangyouxiayiye h6 white" v-if="multipleStores == 1"></text>
				</view>
				<view class="d-flex a-center m-bot10">
					<text class="iconfont icon-a-zu1418 m-right10"></text>
					<view class="ellipsis">{{ storeInfo.address }}</view>
				</view>
			</view>
			<u-loading-icon :show="!storeInfo && way == 0" mode="semicircle" text="正在加载门店信息" size="16" color="#fff"
				textColor="#fff"></u-loading-icon>
			<view class="p-left30 w-fit" v-if="way == 1" @click="selectAddress">
				<view class="size32 ellipsis m-bot10" v-if="Address.Aaddress">{{ Address.Aregion }}{{ Address.Aaddress }}</view>
				<view class="size32" v-else>请选择收货地址<text class="iconfont icon-xiangyouxiayiye h6 white m-left10"></text></view>
				<view class="d-flex a-center m-bot10" v-if="Address.Amobile">
					<text class="m-right10">{{ $pop.hidePhone(Address.Amobile) }}</text>
					<text>{{ Address.Aname }}</text>
				</view>
			</view>
		</view>

		<view class="swiper p-re hidden" :class="{'active': hide}" v-if="storeInfo && storeInfo.recommend">
			<swiper class="swiper p-ab width" autoplay :display-multiple-items="2" next-margin="56rpx">
				<swiper-item v-for="(item,index) in storeInfo.recommend" :key="index" @click="toUrl(item.route)">
					<view class="wh p-left20 bor_radius_4">
						<image :src="$imgUrls(item.img)" mode="aspectFill"></image>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<view class="content flex-1 d-flex p-top24 bgwhite zIndex" v-if="pageData.length">
			<scroll-view scroll-y class="left" :scroll-into-view="`left${leftIndex}`" scroll-with-animation>
				<view class="item size26 color_66" :class="{'active': leftIndex == index}" :id="`left${index}`"
					v-for="(item,index) in pageData" :key="index" @click="tabClick(index)">{{ item.classify_name }}</view>
				<view class="p-bot120"></view>
			</scroll-view>
			<scroll-view scroll-y class="flex-1 p-left24 p-right24" :scroll-top="scrollTop" @scroll="rightScroll"
				refresher-enabled :refresher-triggered="triggered" refresher-default-style="none" @refresherrefresh="onRefresh">
				<view :id="`right${index}`" v-for="(item,index) in pageData" :key="index">
					<image :src="$imgUrls(item.classify_atlas)" mode="widthFix" class="bor_radius_16 m-bot24"
						v-if="item.classify_atlas"></image>
					<view class="m-bot24">
						<view class="size30 bold">{{ item.classify_name }}</view>
						<view class="size22 color_66 m-top4" v-if="item.classify_info">{{ item.classify_info }}</view>
					</view>
					<view v-if="item.goods">
						<view class="good-item d-flex" v-for="(subItem,subIndex) in item.goods" :key="subIndex"
							@click="toGoods(subItem.goods_id, `${subItem.store_id}&mode=1`)">
							<image :src="$imgUrls(subItem.img)" mode="aspectFill" class="good_img bor_radius_4"></image>
							<view class="flex-1 p-left24">
								<view class="area">
									<view class="size28">{{ subItem.name }}</view>
									<view class="size22 color_66 ellipsis_2 m-top10">{{ subItem.info }}</view>
								</view>
								<view class="d-flex a-center m-top10">
									<view class="flex-1 color_E9">
										<text>￥</text><text class="size28 bold m-right10">{{ parseFloat(subItem.price) }}</text>
										<text class="color_66 line-through"
											v-if="parseFloat(subItem.price) < parseFloat(subItem.full_price)">￥{{ parseFloat(subItem.full_price) }}</text>
									</view>
									<!-- carNum：所选规格数量、goodsNum：商品总数、无规格时相等 -->
									<text class="iconfont icon-jianshao1 size42 thmeColor" @click.stop="handleDel(subItem)"
										v-if="subItem.carNum > 0"></text>
									<view class="amount size26 color_33 text-center" v-if="subItem.carNum > 0">
										{{ subItem.goodsNum }}</view>
									<text class="iconfont icon-zengjia size42 thmeColor" @click.stop="handleAdd(subItem)"></text>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="h7 color_99 text-center p-bot140">我是有底线的~</view>
			</scroll-view>
		</view>

		<empty class="bgwhite zIndex" cat='4' msg='暂无数据' v-if="noData"></empty>

		<view class="CartView bgwhite d-flex a-center hidden" v-if="cartList.length" @click="showCartList = !showCartList">
			<view class="m-left30 p-re">
				<text class="iconfont icon-gouwuche size50 color_66"></text>
				<view class="Cartnum thmeBg bor_radius h7 white flexac p-ab">{{ allNum }}</view>
			</view>
			<view class="flex-1 color_E9 bold m-left20">
				<text>￥</text><text class="size30">{{ allPrice }}</text>
			</view>
			<view class="Settle height thmeBg size28 white flexac" @click.stop="settlement">去结算</view>
		</view>

		<view class="Controls wh d-flex a-end" v-if="showCartList && cartList.length" @click="showCartList = false">
			<view class="botPop width bgwhite bor_radius_top10" @click.stop>
				<view class="d-flex padding30 bot">
					<view class="dot flexac m-right20" :class="{'thmeBg thmeBorder': selectAll}" @click="cancelAll">
						<text class="iconfont icon-xuanzhong size26 white"></text>
					</view>
					<view class="flex-1 size26 color_33 bold">已选商品({{allNum}}件)</view>
					<view class="d-flex a-center color_99" @click="clearCart">
						<text class="iconfont icon-shanchu2 size28"></text>
						<text class="size26 m-left10">清空购物车</text>
					</view>
				</view>
				<view class="swipe-action">
					<view class="padding20-30 d-flex a-center" v-for="(item,index) in cartList" :key="index"
						@click="toGoods(item.goods_id, `${item.store_id}&mode=1`)">
						<view class="dot flexac m-right30" :class="{'thmeBg thmeBorder': item.checked}"
							@click.stop="handleCheck(index)">
							<text class="iconfont icon-xuanzhong size26 white"></text>
						</view>
						<image :src="$imgUrls(item.goodsImg)" mode="aspectFill" class="img bor_radius_4"></image>
						<view class="flex-1 m-left20">
							<view class="size26 ellipsis">{{item.goods_name}}</view>
							<view class="size22 color_66 ellipsis m-top10">{{item.operation_text}}</view>
							<view class="d-flex a-center m-top20">
								<view class="flex-1 color_E9"><text>￥</text><text class="size26 bold">{{ item.price }}</text>
								</view>
								<text class="iconfont icon-jianshao1 size40 thmeColor" @click.stop="delBtn(item.car_id)"></text>
								<view class="amount size26 color_33 text-center">{{ item.num }}</view>
								<text class="iconfont icon-zengjia size40 thmeColor" @click.stop="addBtn(item.car_id)"></text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<tabBar :tab="4"></tabBar>
		<showModel @cancelFunc='showModal=false' goHome='0' v-if='showModal' type='2'></showModel>
	</view>
</template>

<script>
	import { mapState } from 'vuex'
	export default {
		data() {
			return {
				pageData: [],
				storeInfo: '',
				Address: '',
				cartList: [],
				showCartList: false,
				way: 0, // 0自提 1外送（diy入口） 
				shop_id: '',
				multipleStores: 0, // 多门店为1
				leftIndex: 0,
				scrollTop: 0, // 竖向滚动条位置
				fastClick: false,
				showModal: false,
				noData: false,
				hide: false,
				triggered: false // 设置当前下拉刷新状态
			}
		},
		computed: {
			...mapState(['color', 'System', 'navWidth', 'navHeight', 'totalHeight', 'startUp', 'vid', 'share']),
			allNum() {
				let num = 0
				this.cartList.forEach(item => {
					if (item.checked) num += parseInt(item.num)
				})
				return num
			},
			allPrice() {
				let price = 0
				this.cartList.forEach(item => {
					if (item.checked) price += item.price * item.num
				})
				return price.toFixed(2)
			},
			selectAll() {
				let list = this.cartList.filter(item => item.checked)
				return this.cartList.length == list.length
			}
		},
		onLoad(e) {
			this.$pop.getLocation()
			if (e.shop_id) this.shop_id = e.shop_id
			if (e.way) this.way = e.way
			if (this.startUp.delivery.indexOf('2') == -1) this.way = 1
			if (this.startUp.delivery.indexOf('1') == -1) this.way = 0
			this.$showLoading('')
			// 优先显示缓存
			const result = uni.getStorageSync('repastData')
			if (result) {
				this.pageData = result
				this.$hideLoading()
			}
		},
		onShow() {
			this.topCategory()
			if (this.shop_id) this.getCart()
			this.getAddress()
		},
		onUnload() {
			uni.setStorageSync('repastData', this.pageData)
		},
		methods: {
			toStores() {
				if (!this.multipleStores) return
				this.toUrl('/otherPage/custom/selectStore')
			},
			topCategory() {
				this.noData = false
				this.$http.post({
					url: '/singleSaleApi/allUpList',
					data: {
						mode: 1,
						shop_id: this.multipleStores == 1 ? this.shop_id : '',
						getGpec: 'getState' // getGoodsSpecs会返回true/false
					}
				}).then(res => {
					this.pageData = res.data || []
					this.storeInfo = res.storeInfo || ''
					this.multipleStores = res.multipleStores
					if (!this.shop_id) {
						this.shop_id = this.storeInfo.shop_id || ''
						this.getCart()
					}
					if (!this.pageData.length) this.noData = true
					setTimeout(() => {
						let oneTop = 0
						this.pageData.forEach((item, index) => {
							this.$getViewInfo(`#right${index}`).then(data => {
								if (!data) return
								if (data.id == 'right0') oneTop = data.top
								item.top = data.top - oneTop
							})
						})
						this.$hideLoading()
					}, 1000)
				})
			},
			getCart() {
				this.$http.post({
					url: '/zzj_singleSaleApi/cartList',
					data: {
						shop_id: this.shop_id
					}
				}).then(res => {
					if (res.errcode != 100) return this.$Toast(res.msg)
					let result = res.data || []
					this.cartList = result.map(item => ({ ...item, checked: true }))
				})
			},
			getAddress() {
				this.$http.post({
					url: '/SRA_simMallApi/getOldAddress',
					data: {
						type: 3
					}
				}).then(res => {
					if (res.code != 100) return this.$Toast(res.msg)
					this.Address = res.data || ''
				})
			},
			switchMode(index) {
				if (!this.vid) return this.showModal = true
				if (index == 1 && !this.Address.Aaddress) return this.toUrl('/orderPage/Addresslist/Addresslist')
				this.way = index
			},
			selectAddress() {
				if (!this.vid) return this.showModal = true
				this.toUrl('/orderPage/Addresslist/Addresslist')
			},
			clearCart() { // 清空购物车
				if (!this.vid) return this.showModal = true
				this.$Modal('提示', '确定不要了吗？').then(res => {
					if (!res) return
					this.$http.post({
						url: '/zzj_singleSaleApi/emptyMyCart'
					}).then(res => {
						if (res.errcode != 100) return this.$Toast(res.msg)
						this.topCategory()
						this.getCart()
					})
				})
			},
			incCart(car_id, num) { // 改变某商品加购数量
				if (!this.vid) return this.showModal = true
				this.$http.post({
					url: '/zzj_singleSaleApi/incCart',
					data: {
						car_id,
						num
					}
				}).then(res => {
					if (res.errcode != 100) return this.$Toast(res.msg)
					this.topCategory()
					this.getCart()
				})
			},
			delCart(car_id, index) { // 某商品移出购物车
				if (!this.vid) return this.showModal = true
				this.$http.post({
					url: '/zzj_singleSaleApi/delCart',
					data: {
						car_id
					}
				}).then(res => {
					if (res.errcode != 100) return this.$Toast(res.msg)
					this.cartList.splice(index, 1)
					this.topCategory()
				})
			},
			joinCart(item) {
				if (!this.vid) return this.showModal = true
				this.$http.post({
					url: '/zzj_singleSaleApi/joinCart',
					data: {
						num: 1,
						goods_id: item.goods_id,
						shop_id: item.store_id
					}
				}).then(res => {
					if (res.errcode != 100) return this.$Toast(res.msg)
					this.topCategory()
					this.getCart()
				})
			},
			delBtn(car_id) {
				const index = this.cartList.findIndex(n => n.car_id == car_id)
				if (this.cartList[index].num > 1) {
					this.incCart(car_id, this.cartList[index].num - 1)
					return
				}
				this.delCart(car_id, index)
			},
			addBtn(car_id) {
				const index = this.cartList.findIndex(n => n.car_id == car_id)
				this.incCart(car_id, parseInt(this.cartList[index].num) + 1)
			},
			handleDel(item) {
				let cars = this.cartList.filter(n => n.goods_id == item.goods_id)
				if (cars.length == 1) return this.delBtn(cars[0].car_id)
				this.$Toast('不同规格的商品需在购物车中减购')
				this.showCartList = true
			},
			handleAdd(item) {
				console.log(item)
				if (item.stock == 0) return this.$Toast('库存不足')
				// 有规格
				if (item.getGoodsSpecs) return this.toGoods(item.goods_id, `${item.store_id}&mode=1`)
				// false
				if (item.carNum > 0) { // 已在购物车
					let result = this.cartList.find(n => n.goods_id == item.goods_id)
					if (result) this.addBtn(result.car_id)
				} else { // 未被加购
					this.joinCart(item)
				}
			},
			handleCheck(index) {
				this.cartList[index].checked = !this.cartList[index].checked
			},
			cancelAll() {
				let bool = this.selectAll ? false : true
				this.cartList.forEach(item => {
					item.checked = bool
				})
			},
			settlement() {
				if (!this.vid) return this.showModal = true
				if (!this.allNum) return this.$Toast('请至少选择一个商品')
				if (!this.Address.Aaddress && this.way == 1) return this.$Toast('需添加收货地址才能开启外送服务')
				let car_ids = []
				this.cartList.forEach(item => {
					if (item.checked) car_ids.push(item.car_id)
				})
				if (!car_ids.length) return
				let delivery = this.way == 0 ? 2 : 1
				// 把数组中的所有元素转换为一个字符串
				this.toUrl(`/orderPage/order/createOrders?car_id=${car_ids.join()}&delivery=${delivery}`)
			},
			tabClick(index) {
				this.leftIndex = index
				this.scrollTop = this.pageData[index].top
				this.fastClick = true
			},
			rightScroll(e) {
				if (this.fastClick) return this.fastClick = false
				if (e.detail.scrollTop > 10) this.hide = true
				this.pageData.forEach((item, index) => {
					if (e.detail.scrollTop >= item.top) {
						this.leftIndex = index
					}
				})
			},
			scrolltoupper(e) { // 滚动到顶部时触发
				if (e.detail.direction == 'top') this.hide = false
			},
			onRefresh() {
				this.triggered = true
				setTimeout(() => {
					this.triggered = false
					if (this.hide) this.hide = false
				}, 100)
			}
		},
		onShareAppMessage() {
			return {
				title: this.share.title,
				desc: this.share.desc,
				path: `/pages/index/index?share_v_id=${this.vid}&pageType=999`,
				imageUrl: this.share.imageUrl
			}
		}
	}
</script>

<style lang="scss" scoped>
	.repastPage {
		height: 100vh;

		.topBg {
			height: calc(346rpx + var(--total-height));
			position: fixed;
			top: 0;
			left: 0;
			background-color: var(--color);
			background-repeat: no-repeat;
			background-size: 100% auto;
		}

		.head {
			min-height: calc(130rpx + var(--total-height));
		}

		.content {
			min-height: 0;
		}
	}

	.tab {
		font-size: 32rpx;

		&.active {
			font-size: 44rpx;
			font-weight: bold;
		}
	}

	.line {
		width: 2rpx;
		height: 32rpx;
	}

	.search {
		width: 60rpx;
		height: 60rpx;
		background: rgba(51, 51, 51, 0.1);
	}

	.left {
		width: 150rpx;
		border-right: 2rpx solid #efefef;
		box-sizing: border-box;

		.item {
			padding: 30rpx 20rpx;

			&.active {
				color: #333;
				font-weight: bold;
				border-right: 4rpx solid var(--color);
			}
		}
	}

	.good-item {
		margin-bottom: 56rpx;

		.good_img {
			width: 164rpx;
			height: 164rpx;
		}

		.area {
			min-height: 100rpx;
		}
	}

	.amount {
		width: 60rpx;
	}

	.CartView {
		width: 690rpx;
		height: 90rpx;
		border-radius: 45rpx;
		position: fixed;
		left: 30rpx;
		bottom: calc(130rpx + constant(safe-area-inset-bottom));
		bottom: calc(130rpx + env(safe-area-inset-bottom));
		z-index: 200;
		box-shadow: 0 6rpx 20rpx #fee0e3;

		.Cartnum {
			width: 36rpx;
			height: 36rpx;
			top: -18rpx;
			right: -18rpx;
		}

		.Settle {
			width: 180rpx;
		}
	}

	.Controls {
		background-color: rgba(0, 0, 0, 0.2);
		position: fixed;
		top: 0;
		left: 0;
		z-index: 100;

		.botPop {
			padding-bottom: calc(220rpx + constant(safe-area-inset-bottom));
			padding-bottom: calc(220rpx + env(safe-area-inset-bottom));
		}

		.swipe-action {
			max-height: 50vh;
			overflow-x: hidden;
			overflow-y: auto;

			.img {
				width: 130rpx;
				height: 130rpx;
			}
		}

		.dot {
			width: 34rpx;
			height: 34rpx;
			border: 1px solid #999;
			border-radius: 50%
		}
	}

	.swiper {
		height: 432rpx;
		transition: height 0.5s;

		&.active {
			height: 0;
		}

		.swiper {
			bottom: 0;
			left: 0;
		}
	}

	/deep/ .u-loading-icon {
		justify-content: flex-start !important;
		padding-left: 30rpx;
	}
</style>